/**
 *
 * 此demo只是一个简单的调用示例，不适合用到实际生产环境中
 *
 * 大模型 WebAPI 接口调用示例 接口文档（必看）：https://www.xfyun.cn/doc/spark/Web.html#_1-%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
 * 错误码链接：
 * https://www.xfyun.cn/doc/tts/online_tts/API.html
 * https://www.xfyun.cn/document/error-code （code返回错误码时必看）
 *
 */

import CryptoJS from 'crypto-js'
import VConsole from 'vconsole'

// 地址必须填写，代表着大模型的版本号！！！！！！！！！！！！！！！！
let httpUrl = new URL("https://spark-api.xf-yun.com/v4.0/chat");
// 动态获取
let modelDomain;
//APPID，APISecret，APIKey在https://console.xfyun.cn/services/cbm这里获取
const APPID = '64112601'
const API_SECRET = 'NzY1NmVhMmE3NzE0YTRiMDE2NDUyNDY4'
const API_KEY = '4d29c1aff36b85e66c0b6b3acbf6d2ce'


function getWebsocketUrl() {
    // 动态获取domain信息
    switch (httpUrl.pathname) {
        case "/v1.1/chat":
            modelDomain = "general";
            break;
        case "/v2.1/chat":
            modelDomain = "generalv2";
            break;
        case "/v3.1/chat":
            modelDomain = "generalv3";
            break;
        case "/v3.5/chat":
            modelDomain = "generalv3.5";
            break;
        case "/v4.0/chat":
            modelDomain = "4.0Ultra";
            break;
        case "chat/max-32k":
            modelDomain = "max-32k";
            break;
    }

    return new Promise((resolve, reject) => {
        var apiKey = API_KEY
        var apiSecret = API_SECRET
        var url = 'wss://' + httpUrl.host + httpUrl.pathname
        var host = location.host
        var date = new Date().toGMTString()
        var algorithm = 'hmac-sha256'
        var headers = 'host date request-line'
        var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrl.pathname} HTTP/1.1`
        var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
        var signature = CryptoJS.enc.Base64.stringify(signatureSha)
        var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
        var authorization = btoa(authorizationOrigin)
        url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
        resolve(url)
    })
}

export class TTSRecorder {
    constructor({
        appId = APPID,
    } = {}) {
        this.appId = appId
        this.status = 'init'
    }


    // 启动
    start(text) {
        this.connectWebSocket(text)
    }

    // 变更状态
    setStatus(status) {
        this.status = status
    }

    // 连接websocket
    connectWebSocket(text) {
        return getWebsocketUrl().then(url => {
            let ttsWS
            if ('WebSocket' in window) {
                ttsWS = new WebSocket(url)
            } else if ('MozWebSocket' in window) {
                ttsWS = new MozWebSocket(url)
            } else {
                alert('浏览器不支持WebSocket')
                return
            }
            this.ttsWS = ttsWS
            ttsWS.onopen = e => {
                this.webSocketSend(text)
            }
            ttsWS.onmessage = e => {
                this.result(e.data)
            }
            ttsWS.onerror = e => {
                clearTimeout(this.playTimeout)
                this.setStatus('error')
                console.error(`详情查看：${encodeURI(url.replace('wss:', 'https:'))}`)
            }
            ttsWS.onclose = e => {
                console.log(e)
            }
        })
    }


    // websocket发送数据
    webSocketSend(text) {
        var params = {
            "header": {
                "app_id": this.appId,
                "uid": "fd3f47e4-d"
            }, "parameter": {
                "chat": {
                    "domain": modelDomain,
                    "temperature": 0.5,
                    "max_tokens": 1024
                }
            },
            "payload": {
                "message": {
                    "text": [
                        {
                            "role": "user", "content": text
                        }
                    ]
                }
            }
        }
        this.ttsWS.send(JSON.stringify(params))
    }

    // websocket接收数据的处理
    result(resultData) {
        let jsonData = JSON.parse(resultData)
        // 提问失败
        if (jsonData.header.code !== 0) {
            alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`)
            return
        }
        // 回答结束
        if (jsonData.header.code === 0) {
            if (jsonData.header.status === 2) {
                this.ttsWS.close()
                this.status = "end"
            }
        }
    }
}
// ======================暴露接口=============================
var vConsole = new VConsole()
let ttsRecorder = new TTSRecorder()
export default ttsRecorder